package com.zuiacsn.java_gobang.service;

import com.zuiacsn.java_gobang.mapper.UserMapper;
import com.zuiacsn.java_gobang.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserService {
    @Autowired
    UserMapper userMapper;

    /**
     * 用户登录功能
     * @param username
     * @param password
     * @return
     */
    public User login(String username, String password){
        log.info("[login] username="+username);
        User user = userMapper.selectByName(username);
        if(user == null || !user.getPassword().equals(password)){ // 登录失败,返回空对象
            return new User();
        }
        return user;
    }

    /**
     * 用户注册功能
     */
    public User register(String username, String password){
        log.info("[register] username="+username);
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        } catch (org.springframework.dao.DuplicateKeyException e) { // 重复用户名
            return new User();
        }
    }

    public User selectByUserName(String username) {
        return userMapper.selectByName(username);
    }
}
